<template>
    <div class="white-box">
        <div>
            <el-button
                v-hasPermi="['enttp:line:add']"
                class="table-mb"
                type="primary"
                @click="onClickAdd"
                >添加线路</el-button
            >
        </div>

        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">线路名称：</span>
                <el-input
                    placeholder="请输入线路名称"
                    v-model="state.lineName"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">归属网点：</span>
                <selectLoadMore
                    v-model:selectValue="state.outletsSid"
                    v-model:options="state.outletsOptions"
                    value="sid"
                    label="outletsName"
                    popperClass="outlet"
                    placeholder="请选择归属网点"
                    :apiFun="getOutletsOptions"
                />
            </div>
            <div class="task-one__item">
                <span class="task-one__label">线路状态：</span>
                <el-select
                    v-model="state.status"
                    placeholder="请选择状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div>
            <el-button
                class="table-mb"
                v-hasPermi="['enttp:line:del']"
                @click="onClickDel()"
                >批量删除线路</el-button
            >
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="selectionChange"
            @sort-change="sortChange"
        >
            <el-table-column
                type="selection"
                width="55"
                v-hasPermi="['enttp:line:del']"
            />
            <el-table-column
                prop="lineName"
                label="线路名称"
                min-width="150"
                fixed="left"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            ></el-table-column>
            <el-table-column
                prop="startDistrictInfo.fullName"
                label="起点"
                min-width="150"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            ></el-table-column>
            <el-table-column
                prop="endDistrictInfo.fullName"
                label="终点"
                min-width="150"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            ></el-table-column>
            <el-table-column
                prop="outletsName"
                label="归属网点"
                min-width="150"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            ></el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                min-width="100"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{ dictStore.getDictMemberName("data_status", row.status) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }">
                    <MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () => onClickDetails(row.sid),
                                    'v-hasPermi': ['enttp:line:query'],
                                },
                                text: '详情',
                            },
                            {
                                props: {
                                    onClick: () => changeStatus(row.sid),
                                    'v-hasPermi': ['enttp:line:update'],
                                },
                                text: ['停用', '启用'][row.status],
                            },
                            {
                                props: {
                                    onClick: () => onClickEdit(row.sid),
                                    'v-hasPermi': ['enttp:line:edit'],
                                },
                                text: '修改',
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                    'v-hasPermi': ['enttp:line:del'],
                                },
                                text: '删除',
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <el-drawer v-model="state.showDetail" title="线路详情" size="1200">
        <template v-if="detail">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">线路名称</el-col>
                <el-col :span="22">{{ detail.lineName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">线路配置</el-col>
                <el-col :span="22">
                    <el-table
                        class="mb-10"
                        :data="detail.configs"
                        :header-cell-style="{
                            background: '#F5F7FA',
                            textAlign: 'center',
                        }"
                        :cell-style="{
                            textAlign: 'center',
                        }"
                        border
                        max-height="300"
                        element-loading-background="rgba(255, 255, 255, 0.6)"
                    >
                        <el-table-column
                            prop="preserveName"
                            label="保藏类型"
                            min-width="120"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="vehicleName"
                            label="运输方式"
                            min-width="120"
                        >
                        </el-table-column>
                        <el-table-column
                            prop="pricingName"
                            label="计价方式"
                            min-width="300"
                        >
                            <template #default="{ row }">
                                <p v-if="row.pricingType === 1">
                                    {{ row.pricingName }}：{{
                                        fenToYuan(row.weightUnitPrice)
                                    }}元/kg
                                </p>
                                <div v-if="row.pricingType === 2">
                                    {{ row.pricingName }}：
                                    <p
                                        v-for="item in row.sizeSaveDTO"
                                        :key="item.sid"
                                    >
                                        {{ item.normsName }}：{{
                                            fenToYuan(item.unitPrice)
                                        }}元/个
                                    </p>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="短运费" min-width="270">
                            <template #default="{ row }">
                                <!-- 无短运费 -->
                                <span v-if="row.shortType === 1">无</span>
                                <!-- 有短运费 -->
                                <template v-if="row.shortType === 0">
                                    <span v-if="row.pricingType === 1"
                                        >免费重量：{{
                                            row.shortWeightSaveDTO.freeWeight
                                        }}kg，超出单位价：{{
                                            fenToYuan(
                                                row.shortWeightSaveDTO.unitPrice
                                            )
                                        }}元/kg</span
                                    >
                                    <span v-if="row.pricingType === 2"
                                        >免费体积：{{
                                            row.shortSizeSaveDTO.freeSize
                                        }}m³，超出单位价：{{
                                            fenToYuan(
                                                row.shortSizeSaveDTO.unitPrice
                                            )
                                        }}元/m³</span
                                    >
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">线路起点</el-col>
                <el-col :span="22">{{
                    detail.startDistrictInfo.fullName
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">线路途径点</el-col>
                <el-col :span="22">
                    <p
                        v-for="item in detail.routeDistrictInfo"
                        :key="item.areaCode"
                    >
                        {{ item.fullName }}
                    </p>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">线路终点</el-col>
                <el-col :span="22">{{
                    detail.endDistrictInfo.fullName
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">预计耗时</el-col>
                <el-col :span="22">{{ detail.estimatedDuration }}天</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">归属网点</el-col>
                <el-col :span="22">{{ detail.outletsName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">备注</el-col>
                <el-col :span="22">{{ detail.note }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">状态</el-col>
                <el-col :span="22">{{
                    dictStore.getDictMemberName("data_status", detail.status)
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">创建时间</el-col>
                <el-col :span="22">{{ detail.created }}</el-col>
            </el-row>
            <!-- 提货信息 -->
            <el-divider content-position="left" border-style="dashed"
                ><el-text type="info" size="small"
                    >提货信息</el-text
                ></el-divider
            >
            <el-row :gutter="20" class="mb-20">
                <el-col :span="2" align="end">提货方式</el-col>
                <el-col :span="22">{{
                    dictStore.getDictMemberName(
                        "line_delivery_type",
                        detail.deliveryType
                    )
                }}</el-col>
            </el-row>
            <template v-if="detail.deliveryType === 0 && detail.pickers">
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="2" align="end">提货员</el-col>
                    <el-col :span="22">
                        <el-table
                            :data="detail.pickers"
                            row-key="sid"
                            :header-cell-style="{
                                background: '#F5F7FA',
                                textAlign: 'center',
                            }"
                            :cell-style="
                                ({ column }) => {
                                    return {
                                        textAlign:
                                            column.className === 'operation-nav'
                                                ? 'left'
                                                : 'center',
                                        paddingLeft:
                                            column.className === 'operation-nav'
                                                ? '25px'
                                                : '0',
                                    };
                                }
                            "
                            border
                            max-length="300"
                            element-loading-background="rgba(255, 255, 255, 0.6)"
                        >
                            <el-table-column
                                prop="nickName"
                                label="昵称"
                                min-width="200"
                                fixed="left"
                            ></el-table-column>
                            <el-table-column label="头像" min-width="200">
                                <template #default="{ row }">
                                    <Image :src="row.avatar" :size="40" />
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="phone"
                                label="手机号"
                                min-width="200"
                            ></el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
            </template>
            <template v-if="detail.deliveryType === 1 && detail.entdlvInfo">
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="2" align="end">企业名称</el-col>
                    <el-col :span="22">{{
                        detail.entdlvInfo.entdlvName
                    }}</el-col>
                </el-row>
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="2" align="end">企业地址</el-col>
                    <el-col :span="22">{{ detail.entdlvInfo.address }}</el-col>
                </el-row>
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="2" align="end">联系人</el-col>
                    <el-col :span="22">{{
                        detail.entdlvInfo.contactName
                    }}</el-col>
                </el-row>
                <el-row :gutter="20" class="mb-20">
                    <el-col :span="2" align="end">联系电话</el-col>
                    <el-col :span="22">{{
                        detail.entdlvInfo.contactPhone
                    }}</el-col>
                </el-row>
            </template>
        </template></el-drawer
    >
</template>

<script setup>
import { inject, reactive, onMounted, onActivated, toRefs } from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import {
    getLines,
    getLineDetail,
    delLines,
    changeLineStatus,
    getLineConfigs,
    getLineUsers,
    getLineEntdlvs,
} from "@/apis/enterprise/line.js";
import { getOutlets } from "@/apis/outlet/outlet.js";
import selectLoadMore from "@/components/selectLoadMore.vue";
import Image from "@/components/Image.vue";
import { fenToYuan } from "@/assets/common/utils.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore.getDictMembers("line_delivery_type");

const router = useRouter();
const $message = inject("$message");

const state = reactive({
    statusList: [],
    ascended: false,
    sortFieldName: null,
    lineName: null,
    outletsSid: null,
    status: null,
    outletsOptions: [],
    sidList: [],
    showDetail: false,
    detail: null,
});
const { detail } = toRefs(state);

onMounted(() => {});

onActivated(() => {
    pubParams(getList);
});

const getOutletsOptions = async (params) => {
    const res = await getOutlets({
        ...params,
        outletsName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 是否包含短运费
const getShortPrice = (config) => {
    if (config.shortType === 0) {
        const { freeSize, sizeShortPrice, freeWeight, weightShortPrice } =
            config;
        if (freeSize && sizeShortPrice) {
            return `${freeSize}m³内免费，超出按${(sizeShortPrice / 100).toFixed(
                2
            )}元/m³计费`;
        } else if (freeWeight && weightShortPrice) {
            return `${freeWeight}kg内免费，超出按${(
                weightShortPrice / 100
            ).toFixed(2)}元/kg计费`;
        }
    } else {
        return "不包含";
    }
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getLines({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            lineName: state.lineName,
            outletsSid: state.outletsSid,
            status: state.status,
        })
    );
}

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 跳转到新增页
const onClickAdd = () => {
    router.push({ name: "LineAdd" });
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

// 点击修改按钮
const onClickEdit = (sid) => {
    sid &&
        router.push({
            name: "LineEdit",
            query: {
                sid,
            },
        });
};

// 跳转详情
const onClickDetails = async (sid) => {
    state.showDetail = true;
    state.detail = null;
    await getDetails(sid);
    switch (state.detail.deliveryType) {
        case 0:
            getUser();
            break;
        case 1:
            getEntdlv();
            break;
    }
    getConfigs(sid);
};

const getDetails = async (sid) => {
    const res = await getLineDetail({ sid });
    if (res.data.code == 200) {
        state.detail = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 根据线路ID查询线路绑定的提货员
const getUser = async () => {
    const res = await getLineUsers({ sid: state.detail.sid });
    if (res.data.code == 200) {
        state.detail.pickers = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 根据线路ID查询线路绑定的提货企业
const getEntdlv = async () => {
    const res = await getLineEntdlvs({ sid: state.detail.sid });
    if (res.data.code == 200) {
        state.detail.entdlvInfo = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getConfigs = async (sid) => {
    const res = await getLineConfigs({ sid });
    if (res.data.code == 200) {
        state.detail.configs = res.data.data;
        state.detail.configs.forEach((item) => {
            const pricingType = item.pricingValue;
            item.pricingType = pricingType;

            if (pricingType === 1) {
                // 按重量
                if (item.shortType === 0) {
                    // 含短运费
                    item.shortWeightSaveDTO = {
                        freeWeight: item.freeWeight,
                        unitPrice: item.weightShortPrice,
                    };
                }
            }
            if (pricingType === 2) {
                // 按体积
                if (item.shortType === 0) {
                    // 含短运费
                    item.shortSizeSaveDTO = {
                        freeSize: item.freeSize,
                        unitPrice: item.sizeShortPrice,
                    };
                }
                // 装箱规格
                item.sizeSaveDTO = item.configSize.map(
                    ({ norms, sizeUnitPrice }) => {
                        return {
                            normsSid: norms.sid,
                            normsName: `${norms.normsName}(${norms.normsLength} * ${norms.normsWide} * ${norms.normsHigh})`,
                            unitPrice: sizeUnitPrice,
                        };
                    }
                );
            }
        });
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 切换状态
const changeStatus = async (sid) => {
    const res = await changeLineStatus({ sid });
    if (res.data.code == 200) {
        $message({ message: "操作成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 选中项改变
const selectionChange = (e) => {
    state.sidList = e.map((item) => item.sid);
};

// 删除
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除线路吗？");
    const res = await delLines({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};
</script>

<style lang="less" scoped></style>
